<template>
  <ocrImport
    class="basic-form"
    ref="steps"
    :type="type === '01' ? 'zhouzhuanfanghetongshu':'feizhuzhai'"
    :steps="steps"
    :autoNext="false"
    @scanCompleted="handleScanCompleted"
  >
    <!-- 步骤1：表单 -->
    <div class="step1">
      <div class="card-title">
        承租方信息
        <el-button type="primary" size="small" @click="$refs.clientSelect.show()" v-if="!unEdit">选择承租方</el-button>
      </div>

      <el-form class="basicPadding mt20 form-wrap" :model="propForm" size="small" ref="propForm">
        <el-form-item label="承租方名称:">{{propForm.clientLesseeName}}</el-form-item>
        <el-form-item label="承租方类型:">{{baseInfo.lessee}}</el-form-item>
        <el-form-item v-show="propForm.clientLesseeType==0" label="证件类型:">{{baseInfo.personageCertificate}}</el-form-item>
        <el-form-item v-show="propForm.clientLesseeType!=0" label="证件类型:">{{baseInfo.commercialCertificate}}</el-form-item>
        <el-form-item label="证件号码:">{{propForm.certificateNum}}</el-form-item>
        <template v-show="propForm.clientLesseeType!=0">
          <el-form-item label="法人代表:">{{propForm.legalPerson}}</el-form-item>
          <el-form-item label="身份证号码:">{{propForm.legalIdentityCard}}</el-form-item>
          <el-form-item label="手机号码:">{{propForm.phoneNum}}</el-form-item>
          <el-form-item label="联系电话:">{{propForm.telephone}}</el-form-item>
          <el-form-item label="详细地址:">{{propForm.address}}</el-form-item>
          <el-form-item label="行业类别:">{{propForm.categroyEmployment}}</el-form-item>
          <el-form-item label="产业引进部门:">{{propForm.introduceUnit}}</el-form-item>
          <el-form-item label="联系人:">{{propForm.name}}</el-form-item>
          <el-form-item label="联系人电话:">{{propForm.phone}}</el-form-item>
        </template>
      </el-form>

      <div class="card-title">
        物业信息
        <el-button type="primary" size="small" @click="$refs.roomSelect.show('1',formData.rentContractId)" v-if="!unEdit">添加物业</el-button>
      </div>
      <el-table class="mt20" :data="propertyInformation" stripe align="left">
        <el-table-column label="物业名称" align="left" prop="propertyName" width="150" />
        <el-table-column align="left" label="建筑面积（㎡）" prop="buildingArea" width="100" />
        <el-table-column align="left" label="市场评估租金单价（元/㎡/月）" prop="assessPrice" width="100" />
        <el-table-column align="left" prop="price" label="租赁单价（元/㎡/月）" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" :disabled="unEdit" v-only-number="{min:0, max:10000, precision:2}" />
          </template>
        </el-table-column>
        <el-table-column align="left" prop="remarks" label="说明" width="100">
          <template slot-scope="scope">
            <el-input v-halfCharCode v-model="scope.row.remarks" :disabled="unEdit" maxlength="100" />
          </template>
        </el-table-column>
        <el-table-column align="left" width="80" label="操作" v-if="!unEdit">
          <template slot-scope="scope">
            <el-button @click="deleteList(scope.$index, 'propertyInformation')" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="card-title mt20">合同信息</div>

      <el-form :model="formData" class="basicPadding mt20 reset form-wrap" size="small" :rules="rules_formData" ref="formData">
        <el-form-item label="合同编号" prop="contractCode">
          <el-input v-halfCharCode placeholder="请输入" v-model="formData.contractCode" maxlength="40" readonly />
        </el-form-item>

        <el-form-item label="签订方式" prop="signType">
          <el-select clearable v-model="formData.signType" placeholder="请选择" :disabled="unEdit">
            <el-option v-for="item in rentSigningMethod" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="收取方式" prop="feeType">
          <el-select clearable v-model="formData.feeType" placeholder="请选择">
            <el-option v-for="item in rentFeeType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="自定义收费周期（输入收租周期）" prop="feeTypeValue" v-if="isFeeTypeValue">
          <el-input v-model.number="formData.feeTypeValue" placeholder="请输入" v-only-number="{min:0, max:31, precision:2}" />
        </el-form-item>

        <el-form-item label="应收日（输入每月应收日期）" prop="feeDate">
          <el-input v-model.number="formData.feeDate" placeholder="请输入应收日" v-only-number="{min:0, max:31, precision:0}" />
        </el-form-item>

        <el-form-item label="合同签订日期" prop="signDate">
          <el-date-picker v-model="formData.signDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="unEdit" />
        </el-form-item>

        <el-form-item label="合同开始日期" prop="startDate">
          <el-date-picker v-model="formData.startDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="unEdit" />
        </el-form-item>

        <el-form-item label="合同结束日期" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            @change="((val)=>{changeRentStandard(val,'endDate')})"
          />
        </el-form-item>

        <el-form-item label="装修免租期" prop="freeFees">
          <el-date-picker v-model="freeFees" type="daterange" value-format="yyyy-MM-dd" :disabled="unEdit" />
        </el-form-item>

        <el-form-item label="起租日期" prop="rentStartDate">
          <el-date-picker
            v-model="formData.rentStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            :disabled="unEdit"
            @change="((val)=>{changeRentStandard(val,'rentStartDate')})"
          />
        </el-form-item>

        <el-form-item label="合同类型" class="block">
          <el-input v-halfCharCode readonly :value="rentContractTypeName" />
        </el-form-item>

        <el-form-item label="合同细类" class="block">
          <el-input v-halfCharCode readonly :value="rentContractSubTypeName" />
        </el-form-item>

        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="formData.buildingArea" :min="0" v-only-number="{min:1, max:99999999, precision:2}" :disabled="unEdit" />
        </el-form-item>

        <el-form-item label="月租金" prop="rentAmount">
          <el-input
            v-model="formData.rentAmount"
            v-only-number="{min:0, max:99999999, precision:2}"
            :disabled="unEdit"
            @change="((val)=>{changeRentStandard(val,'rentAmount')})"
          />
        </el-form-item>

        <el-form-item label="审批方式" prop="approveType" v-if="false">
          <el-select clearable v-model="formData.approveType" placeholder="请选择">
            <el-option v-for="item in rentContractApproveType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="管理所" prop="administrativeOffice">
          <el-select clearable v-model="formData.administrativeOffice" placeholder="请选择物业关联管理所">
            <el-option v-for="item in administrativeOffice" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="产业引进部门" prop="importDept" v-if="false">
          <el-input v-halfCharCode placeholder="请输入产业引进部门" v-model="formData.importDept" />
        </el-form-item>

        <el-form-item label="地址" prop="address" v-if="false">
          >
          <el-input v-halfCharCode placeholder="请输入地址" v-model="formData.address" />
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input v-halfCharCode placeholder="请输入内容" v-model="formData.remarks" maxlength="100" />
        </el-form-item>
      </el-form>

      <div class="card-title mt20">
        租金标准
        <el-button type="primary" size="small" @click="addFeeInformation">添加区间</el-button>
      </div>
      <el-form class="mt20" :model="rules_rentFeeInformation" :rules="rules_rentFeeInformation.rules" ref="rules_rentFeeInformation">
        <el-table :data="rules_rentFeeInformation.rentFeeInformation" stripe>
          <el-table-column prop="startDate" align="left" label="开始时间" width="100">
            <template slot-scope="scope">
              <el-form-item :prop="'rentFeeInformation.' + scope.$index + '.startDate'" :rules="rules_rentFeeInformation.rules.startDate">
                <el-date-picker
                  v-model="scope.row.startDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择开始日期"
                  :disabled="scope.row.disabled"
                  @change="handleDateIntervalChange"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="endDate" align="left" label="结束时间" width="100">
            <template slot-scope="scope">
              <el-form-item :prop="'rentFeeInformation.' + scope.$index + '.endDate'" :rules="rules_rentFeeInformation.rules.endDate">
                <el-date-picker
                  v-model="scope.row.endDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择结束日期"
                  :disabled="scope.row.disabled"
                  @change="handleDateIntervalChange"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="priceFinal" label="月租金" align="left" width="100">
            <template slot-scope="scope">
              <el-form-item :prop="'rentFeeInformation.' + scope.$index + '.priceFinal'" :rules="rules_rentFeeInformation.rules.priceFinal">
                <el-input v-model="scope.row.priceFinal" :disabled="scope.row.disabled" v-only-number="{min:0, max:99999999, precision:2}" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="remarks" label="说明" width="100">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-halfCharCode v-model="scope.row.remarks" maxlength="100" :disabled="scope.row.disabled" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column width="100" label="操作" align="left">
            <template slot-scope="scope">
              <el-button
                @click.stop="deleteList(scope.$index, 'rules_rentFeeInformation','rentFeeInformation')"
                type="text"
                :disabled="scope.row.disabled"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div class="card-title mt20">
        其他款项
        <el-button type="primary" size="small" @click="selectFeeItem" v-if="!unEdit">添加费用</el-button>
      </div>
      <el-table class="mt20" align="left" :data="contractFee" style="width: 100%">
        <el-table-column prop="chargeProjectName" align="left" label="费用项目名称" width="180">
          <template slot-scope="scope">
            <el-select clearable v-model="scope.row.feeitemId" placeholder="请选择" :disabled="unEdit">
              <el-option v-for="item in charge_project_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="amount" align="left" label="金额" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.amount" v-only-number="{min:0, max:99999999, precision:2}" :disabled="unEdit" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="180" v-if="!unEdit">
          <template slot-scope="scope">
            <el-button @click.stop="deleteList(scope.$index, 'contractFee')" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 承租方选择 -->
      <client-select ref="clientSelect" :multiple="false" @completeSelect="handleClientChoose" />
      <!-- 物业选择 -->
      <room-select ref="roomSelect" :disabledArr="propertyInformation.map(item => item.roomId)" @completeSelect="handlePropertyChoose" />
    </div>
    <!-- 步骤2：附件 -->
    <div slot="step2" class="step2">
      <h3>文件上传</h3>
      <div class="uploadWrap">
        <v-upload
          ref="rentContractFileUpload"
          :busId="formData.rentContractId"
          modelType="rent-contract"
          @onSuccess="uloadCompleted"
          v-model="uploadFileList"
          multiple
        />
      </div>
    </div>
    <!-- 步骤3：只能计费表单回显 -->
    <template slot="step3">
      <priceTotal :receivableFees="receivableFees" :receivableFees2="receivableFees2" />
    </template>
  </ocrImport>
</template>

<script>
import ocrImport from '@/components/ocr-import'
import editMixins from './edit'
import { addObj, uploadContractFile } from "@/views/wy-rent/api/rent-contract";
import { fetchList as fetchClientList } from "@/views/wy-client/api/clientlessee";
import { getRoomPriceByName } from '@/views/wy-rent/api/rent-price'
export default {
  mixins: [editMixins],
  components: {
    ocrImport,
  },
  computed: {
    steps () {
      return [
        { title: "ocr文件上传" },
        // { title: '选择合同模板', validate: this.handleChooseTemplate },
        { title: '合同基础信息填写', validate: this.contractValidate },
        { title: '上传文件', validate: this.uploadValidate },
        { title: '智能计费', validate: this.handleCompleted },
      ]
    }
  },
  methods: {
    // 扫码识别完成
    async handleScanCompleted ({ data, files }) {
      const loading = this.$loading({
        lock: true,
        text: '文件上传中...',
        spinner: 'el-icon-loading',
      });
      //1、判断有无文件上传
      if (files.length) {
        // 合同附件上传
        let requestData = new FormData();
        requestData.append("file", files[0].raw);
        requestData.append("module", "rentContract");
        requestData.append("busId", this.$route.query.id || "");
        const res = await uploadContractFile(requestData);
        if (res.data.code == 0) {
          this.formData.contractUrl = res.data.data.url;
        }
      }

      // 新增
      const response = await addObj({
        contractUrl: this.formData.contractUrl,
        type: this.type,
        subType: this.subType,
        category: 1
      });
      if (response.data.code == 0) {
        this.$alert("合同初始信息创建成功，请补充合同详细信息");
        await this.showContractData(response.data.data);
        // 扫描数据和表单数据合并↓
        //alert(JSON.stringify(data));

        //可以自动合并的字段
        //合同开始日期、结束日期、装修免租期起、止、建筑面积、月租金
        this.formData = { ...this.formData, rentContractId: response.data.data, ...data }
        //console.log(data);
        //免租期
        this.freeFees = [this.formData.freeFeeStart, this.formData.freeFeeEnd];
        //起租日期，没有免租不是合同开始日期，有则是免租日期的下一天
        if (this.formData.freeFeeEnd != null && this.formData.freeFeeEnd != "") {
          let tempDate = Date.parse(this.formData.freeFeeEnd);
          tempDate = tempDate + 1000 * 60 * 60 * 24;
          let tempDate2 = new Date(tempDate);
          this.formData.rentStartDate = this.getDate(tempDate2);
        }
        else {
          this.formData.rentStartDate = this.formData.startDate;
        }
        //押金手工处理
        if (this.contractFee.length > 0 && this.contractFee[0].feeitemId == '2' && this.contractFee[0].amount == 0) {
          this.contractFee[0].amount = this.formData.otherFee;
        }


        //调价手工处理
        if (this.rules_rentFeeInformation.rentFeeInformation == null || this.rules_rentFeeInformation.rentFeeInformation.length == 0) {
          //第一段默认从起租日期到合同结束日期，如果有第二段，则第一段最前天
          this.rules_rentFeeInformation.rentFeeInformation[0] = { startDate: this.formData.rentStartDate, endDate: this.formData.endDate, priceFinal: this.formData.rentAmount }
          if (this.formData.feePeriod1Start != null) {
            let tempDate = Date.parse(this.formData.feePeriod1Start);
            tempDate = tempDate - 1000 * 60 * 60 * 24;
            let tempDate2 = new Date(tempDate);
            this.rules_rentFeeInformation.rentFeeInformation[0].endDate = this.getDate(tempDate2);
          }

          //如果有第二段加上
          if (this.formData.feePeriod1Start != null) {
            this.rules_rentFeeInformation.rentFeeInformation[1] = { startDate: this.formData.feePeriod1Start, endDate: this.formData.feePeriod1End, priceFinal: this.formData.feeStardard1 }
          }
          //如果有第三段加上
          if (this.formData.feePeriod2Start != null) {
            this.rules_rentFeeInformation.rentFeeInformation[2] = { startDate: this.formData.feePeriod2Start, endDate: this.formData.feePeriod2End, priceFinal: this.formData.feeStardard2 }
          }
        }


        //承租方反查后，显示
        if (this.formData.clientLesseeName != null && this.formData.clientLesseeName != "") {
          let requestData1 = { clientLesseeName: this.formData.clientLesseeName };
          let resp1 = await fetchClientList(requestData1)
          if (resp1.data.code == 0 && resp1.data.data.records != null && resp1.data.data.records.length == 1) {
            let propForm = resp1.data.data.records[0];
            this.formData.customerId = propForm.clientLesseeId;
            this.formData.customerName = propForm.clientLesseeName;
              //产业引进部门
							this.formData.importDept = this.propForm.introduceUnit
            //const propForm = await getClientManage(this.formData.customerId);
            this.propForm = propForm;
            this.clientLesseeType = propForm.clientLesseeType;
            this.showlessee();
          }
          else {
            this.$alert("根据承租方名称没有查询到承租方,请先新增承租方");
          }
        }

        //物业名称，反查后显示
        if (this.formData.propertyName != null && this.formData.propertyName != "") {
          let requestData2 = { propertyName: this.formData.propertyName.replace('深圳市', '').replace('福田区', '') };
          let resp2 = await getRoomPriceByName(requestData2)
          if (resp2.data.code == 0 && resp2.data.data.records != null && resp2.data.data.records.length == 1) {
            let property = resp2.data.data.records[0];
            this.handlePropertyChoose(resp2.data.data.records)
          }
          else {
            this.$alert("根据物业名称没有查询到物业信息,请先新增物业");
          }
        }


        this.$refs.steps.next();
      }
      loading.close()
    }
  },
}
</script>

<style scoped lang="scss">
@import "./edit";
</style>
